﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Web.Handler {

  /// <summary>
  /// 
  /// </summary>
  public class DoAjaxFileUpload : IHttpHandler {

    public void ProcessRequest(HttpContext context) {

      HttpPostedFile file = null;
      string path = string.Empty,
             filename = string.Empty, // 文件名
             error = string.Empty,    // 错误信息
             msg = string.Empty,      // 文件信息
             json = string.Empty;

      file = context.Request.Files["Filedata"];
      path = HttpContext.Current.Server.MapPath("upload") + "\\";

      if (file != null) {

        if (!Directory.Exists(path)) {
          Directory.CreateDirectory(path);
        }

        filename = DateTime.Now.ToString("yyyyMMddHHmmss") + Path.GetExtension(file.FileName);
        file.SaveAs(path + filename);

        msg += "\"File name\": \"" + filename + "\"," +
               "\"File size\": \"" + file.ContentLength + "\",";
      }
      else {
        error = "No file was uploaded.";
      }

      json += "{" +
                "\"error\": \"" + error + "\", " +
                "\"msg\": \"" + msg + "\"" +
              "}";

      context.Response.ContentType = "text/plain";
      context.Response.Write(json);
    }

    public bool IsReusable {
      get {
        return false;
      }
    }
  }
}